﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;

namespace SCWLib
{
    /// <summary>
    /// This helper class is used to Retrieve RSS/Atom Feed
    /// </summary>
    class FeedHelper
    {
        public SyndicationFeed GetFeed(string url)
        {
            //initialize XML Reader to read/parse XML
            XmlReaderSettings settings = new XmlReaderSettings
            {
                IgnoreWhitespace = true,
                CheckCharacters = true,
                CloseInput = true,
                IgnoreComments = true,
                IgnoreProcessingInstructions = true,
                DtdProcessing = DtdProcessing.Prohibit
            };

            //Check if it url is empty, if not, process it
            if (!String.IsNullOrEmpty(url))
            {


                using (XmlReader reader = XmlReader.Create(url, settings))
                {
                    if (reader.ReadState == ReadState.Initial)
                    {
                        reader.MoveToContent();
                        Atom10FeedFormatter atom = new Atom10FeedFormatter();
                        // Check if it is in atom Format return the feed
                        if (atom.CanRead(reader))
                        {
                            atom.ReadFrom(reader);
                            return atom.Feed;
                        }

                        Rss20FeedFormatter rss = new Rss20FeedFormatter();
                        // Check if it is in RSS Format return the feed
                        if (rss.CanRead(reader))
                        {
                            rss.ReadFrom(reader);
                            return rss.Feed;
                        }
                    }

                }
            }
            //Return null when it could not find any feed
            return null;
        }
    }
}
